

use anyhow::Ok;
use base64::{engine::general_purpose::{STANDARD,URL_SAFE}, Engine};

//use crate::cli::base64::Base64Format;
use crate::{input_to_buffer, Base64Format}; // 怎样能这么写  Base64Format , 在上层的lib.rs 里 pub use 了

pub fn process_encode(input: &str, format: Base64Format) -> anyhow::Result<()> {
    let buffer = input_to_buffer(input)?;

    // let encoded =  URL_SAFE.encode(&buffer);
    let encoded =  match format { 
        Base64Format::Standard => STANDARD.encode(buffer),
        Base64Format::UrlSafe => URL_SAFE.encode(buffer),
    };
    println!("{}", encoded);
    Ok(())
}

pub fn process_decode(input: &str,format: Base64Format) -> anyhow::Result<()> {
    let buffer = input_to_buffer(input)?;
    let decoded = match format {
        Base64Format::Standard => STANDARD.decode(buffer)?,
        Base64Format::UrlSafe => URL_SAFE.decode(buffer)?,
    };
    // let decoded = STANDARD.decode(&buffer)?;
    // TODO: decoded data might not be string , we assume this
    let decode_str = String::from_utf8(decoded)? ;
    println!("{}", decode_str.trim());
    Ok(())
}

#[cfg(test)]
mod tests{

    use super::*;


    #[test]
    fn test_process_encode(){
        let input = "cliff.toml";
        let format = super::Base64Format::UrlSafe;
        assert!(process_encode(input, format).is_ok());
    }

    #[test]
    fn test_process_decode(){
        let input = "test/normal.txt";
        let format = super::Base64Format::UrlSafe;
        assert!(process_decode(input, format).is_ok());
        
    }
}

